package com.example.ormsqlsplicingframe1.utlis;

import com.example.ormsqlsplicingframe1.note.JoinFieldMajorKey;
import io.swagger.annotations.ApiModel;
import lombok.SneakyThrows;

import javax.tools.FileObject;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Map;
import java.util.stream.Collectors;

@ApiModel("赋值用")
public class CopyUtils {


    /**
     *
     * @param object 第一个类
     * @param obj  目标类
     */
    @SneakyThrows
    public static Object UpdateCopy(Object object, Object obj){

        for (Field field : object.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            if (field.getAnnotation(JoinFieldMajorKey.class) != null){
                Object value = field.get(object);
                Field returnField = returnField(field, obj);
                returnField.setAccessible(true);
                returnField.set(obj,value);
                continue;
            }
        }

        if (object.getClass().getSuperclass() != Object.class){
           obj = getObjValue(object,obj,object.getClass().getSuperclass(),obj.getClass().getSuperclass());
        }

        return obj;

    }

    /**
     *
     * @param o 主类
     * @param i  拷贝主类
     * @param object 主类Class
     * @param obj 拷贝主类 Class
     */
    @SneakyThrows
    private static Object getObjValue(Object o,Object i,Class<?> object, Class<?> obj) {

        Field[] fields = object.getDeclaredFields();

        //是否找到主键
        boolean isGetField = false;
        for (Field field : fields) {
            field.setAccessible(true);
            if (field.getAnnotation(JoinFieldMajorKey.class) != null){
                Object value = field.get(o);

                Field declaredField = obj.getDeclaredField(field.getName());
                declaredField.setAccessible(true);
                declaredField.set(i,value);
                isGetField = true;
            }
        }

        if (!isGetField){
            if (object.getSuperclass() != Object.class){
                getObjValue(o,i,object.getSuperclass(),obj.getSuperclass());
            }
        }
        return i;
    }

    //返回对应字段
    @SneakyThrows
    private static  Field returnField(Field field, Object object){
        return  object.getClass().getDeclaredField(field.getName());
    }


}
